﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Data_Structures_and_Algorithms.linear_list
{
    /// <summary>
    /// 顺序表
    /// </summary>
    public class SeqList: ILinearList
    {
        /// <summary>
        /// 动态数组
        /// </summary>
        private Object[] objs = new Object[0];
        /// <summary>
        /// 记录当前顺序表的长度
        /// </summary>
        public int Length { get; private set; } = 0;

        public void Delete(int index)
        {
            if (index > Length || index < 1) throw new Exception("超出长度");
            for (int i = index; i > Length; i++)
            { // index位置及其后数据依次前移
                objs[i-1] = objs[i];
            }
            Length--;
        }

        public void Display()
        {
            Console.WriteLine("---------------------");
            int index = 0;
            while (index<Length)
            {
                Console.WriteLine(objs[index]);
                index++;
            }
        }

        public int Find(object data)
        {
            int index = 0;
            while (index < Length)
            {
                if (objs[index].Equals(data)) return index+1;
                index++;
            }
            return -1;
        }

        public object FindAt(int index)
        {
            if (index> Length || index < 1) throw new Exception("超出长度");
            return objs[index - 1];
        }

        public void Insert(int index, object data)
        {
            if (index - 1 > Length||index<1) throw new Exception("超出长度");
            Array.Resize<Object>(ref objs,Length+1); // 增加数组长度；
           
            for (int i = Length; i >= index; i--) { // index-1位置后面数据依次后移
                objs[i] = objs[i-1];
            }
            objs[index - 1] = data;
            Length++;
        }

        public void Update(int index, object data)
        {
            if (index > Length || index < 1) throw new Exception("超出长度");
            objs[index - 1] = data;
        }
    }
}
